package cn.sam416.sample.part0301validation.genericvalidator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class OrderValidator implements Validator {

    @Override
    public boolean supports (Class<?> clazz) {
        return Order.class == clazz;
    }

    @Override
    public void validate (Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors,
                "customerId", "customerId.empty");

        Order order = (Order) target;
        if (order.getCustomerId() != null) {
            Customer customer = getCustomerById(order.getCustomerId());
            if (customer == null) {
                errors.reject("customer.id.invalid",
                        new Object[]{order.getCustomerId()},
                        "Customer id is not valid");
            }
        }
    }

    private Customer getCustomerById (String customerId) {
        //just for test returning null..
        // otherwise we have to use a backend data service here
        return null;
    }
}
